package com.power.filiter;


import com.alibaba.fastjson.JSONObject;
import com.power.contant.AuthConstants;
import com.power.model.SecurityUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * token转换过滤器
 */
@Component
public class TokenTransferFilter extends OncePerRequestFilter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorizationValue)) {
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            if (StringUtils.hasText(token)) {

                //从redis中解决用户功能市场超过当前token的有效期剩余的时长（用户token续约）
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token, TimeUnit.SECONDS);
                if(expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    //续约
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.TOKEN_TIME,TimeUnit.SECONDS);
                }


                //从redis中
                String securityUserJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                //将security安全框架认证用户对象的JSON字符串转换为SecurityUser安全认证对象
                SecurityUser securityUser = JSONObject.parseObject(securityUserJsonStr, SecurityUser.class);
                //获取当前用户的权限集合
                Set<String> perms = securityUser.getPerms();

                //集合转换成集合
                Set<SimpleGrantedAuthority> authorities = perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

                //创建一个用户，密码认证对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser,null,authorities);

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request,response); // 接着运行

    }
}

